package leetcode.oldVersion;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class lc56 {
    public int[][] merge(int[][] intervals) {
        if (intervals.length <= 1) {
            return intervals;
        }

        // 鎸夊尯闂磋捣濮嬩綅缃帓搴�
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));

        ArrayList<int[]> result = new ArrayList<>();
        int[] current = intervals[0];
        result.add(current);

        for (int i = 1; i < intervals.length; i++) {
            int[] next = intervals[i];
            if (current[1] >= next[0]) {
                // 鍚堝苟鍖洪棿
                current[1] = Math.max(current[1], next[1]);
            } else {
                // 涓嶈兘鍚堝苟锛屾坊鍔犳柊鍖洪棿
                current = next;
                result.add(current);
            }
        }

        return result.toArray(new int[result.size()][]);
    }

    public static void main(String[] args) {
        int[][] intervals = {{1, 4}, {4, 5}};
        lc56 solution = new lc56();
        int[][] merged = solution.merge(intervals);
        for (int[] interval : merged) {
            System.out.println(Arrays.toString(interval));
        }
    }
}